/**
 * 编辑项目--js
 * @author cl
 * @date 2019年3月28日
 */
var edit_project = {
	_ID:null,
	_OBJ:null,
	fileArrayPlan:[],
	fileArrayPro:[],
	planObj:null,
	proObj:null,
	fileSplitSize:1024 * 1024 * 10,
	/**
	 * 用户数据集
	 */
	userData:[],
	
	init : function() {
		var obj = GetRequest();
		edit_project._ID = obj.id;
		edit_project.loadUseData();
		edit_project.loadUserSelect();
		edit_project.initDatePicker();
		edit_project.findById(edit_project._ID);
		edit_project.initFileUpload();
	},
	/**
	 * 加载可用用户
	 * 1、可以，0、不可用
	 */
	loadUseData:function(){
		$.ajax({
			url : "/crm/user/loadUserByIsUse", // 请求的url地址
			dataType : "json", // 返回格式为json
			async : false,// 请求是否异步，默认为异步，这也是ajax重要特性
			data : {
				isUse:1
			}, // 参数值
			type : "post", // 请求方式
			success : function(data) {
				edit_project.userData = data;
			},
			error : function() {
			}
		})
	},
	loadUserSelect:function(){
		var html = "";
		$.each(edit_project.userData, function(key, val) {
			html += '<span>';
			html += '<label class="custom_checkbox">';
			html += '<input name="imageType" hidden="hidden" type="checkbox"  value="'+val.uuid+'" data-name="'+val.userRealName+'"/>';
			html += '<div></div>'+val.userRealName+'</label>';
			html += '</span>';
		});
		$(".dj_ns").html(html);
	},
	/**
	 * 日期初始化
	 */
	initDatePicker:function(){
		laydate.render({
			elem: '#beginTime' //开始时间
		});
		laydate.render({
			elem: '#nextStepTime' //开始日期
		});
		laydate.render({
			elem: '#nextStepTimeId' //下一节点时间
		});
	},
	/**
	 * 查询项目详情
	 */
	findById:function(id){
		$.ajax({
			url : "/crm/project/findById", 
			dataType : "json", 
			async : true,
			data : {
				id:id
			},
			type : "post",
			success : function(data) {
				edit_project._OBJ=data;
				$("#proName").val(data.proName);
				$("#liablePerson").val(data.liableUserName);
				$("#beginTime").val(data.beginTime);
				$("#createTime").val(data.createTime);
				$("#nextStepTime").val(data.nextStepTime);
				$("#proRemarks").val(data.proRemarks);
				if (!isBlank(data.teamMembersUuids)) {
					var imageTypes = $("input[name=imageType]");
					$.each(imageTypes, function(key, val) {
						if(data.teamMembersUuids.indexOf(val.value)!=-1){
							val.checked=true;
						}
						
					});
				}
				edit_project.findAccessory();
				edit_project.findProgress();
			},
			error : function() {
				layer.msg("系统错误！", {icon: 2,closeBtn: 0 });;
			}
		});
	},
	/**
	 * 修改保存
	 */
	save:function(_this){
		var proName = $("#proName").val();
		var beginTime = $("#beginTime").val();
		var nextStepTime = $("#nextStepTime").val();
		var proRemarks = $("#proRemarks").val();
		// 必填项的判断
		if(isBlank(proName)) {
			layer.msg("请输入项目名称");
			return false;
		}
		if(isBlank(beginTime)) {
			layer.msg("请选择开始时间");
			return false;
		}
		if(isBlank(nextStepTime)) {
			layer.msg("请选择下一节点时间");
			return false;
		}
		
		var obj = edit_project._OBJ;
		
		var teamMembersUuids ="";
		var teamMembersNames = "";
		$("input[name=imageType]:checked").each(function(i){
			teamMembersUuids += ',' + $(this).val();
			teamMembersNames += ','+$(this).attr("data-name");
		})
		teamMembersUuids = teamMembersUuids.substring(1);
		teamMembersNames = teamMembersNames.substring(1);
		obj.teamMembersUuids=teamMembersUuids;
		obj.teamMembersNames=teamMembersNames;
		
		obj.beginTime=beginTime;
		obj.nextStepTime=nextStepTime;
		obj.proRemarks=proRemarks;
		$.ajax({
			url : "/crm/project/save", 
			dataType : "json", 
			async : true,
			data : obj,
			type : "post",
			success : function(data) {
				if(data.status){
					parent.refreshTabByIndex(0);
					edit_project._OBJ = data.obj;
					var index=layer.alert(data.info, {icon: 1,closeBtn: 0 },function(){ 
//						parent.closeCurPage();
						layer.close(index);
					});
				}else{
					layer.msg(data.info, {icon: 2,closeBtn: 0 });
				}
			},
			error : function() {
				layer.msg("系统错误！", {icon: 2,closeBtn: 0 });;
			}
		});
	},
	resetData:function(){
		$("#proName").val(edit_project._OBJ.proName);
		$("#beginTime").val(edit_project._OBJ.beginTime);
		$("#nextStepTime").val(edit_project._OBJ.nextStepTime);
		$("#proRemarks").val(edit_project._OBJ.proRemarks);
		$(".img_sel2").html('<div id="mySelect2" class="mySelect" ></div>');
		$(".img_sel").html('<div id="mySelect" class="mySelect" ></div>');
		edit_project.initMySelect();
		if (!isBlank(edit_project._OBJ.userUuid)) {
			var userUuid = edit_project._OBJ.userUuid.split(",");
			edit_project.mySelectRadio.setResult(userUuid);
		}
		if (!isBlank(edit_project._OBJ.teamMembersUuids)) {
			var teamMembersUuids = edit_project._OBJ.teamMembersUuids.split(",");
			edit_project.mySelectCheck1.setResult(teamMembersUuids);
		}
	},
	/**
	 * 终止
	 */
	endThis:function(){
		layer.confirm('确定要终止吗?',{btn: ['确定', '取消'],title:"提示"}, function(){
            layer.confirm('再次确认', {btn : ['确定', '取消'], title:"提示"}, function() {
            	var uuid = edit_project._OBJ.uuid;
        		var obj={};
        		obj.uuids = uuid;
        		obj.isEnd = 1;
            	$.ajax({
                    type: "post",
                    url: "/crm/project/setProjectStartOrEnd",
                    data: obj,
                    dataType: "json",
                    async:false,
                    success:function(data) {
                        if(data.status){
                            var index=layer.alert(data.info+"请稍后刷新查看！", {icon: 1},function(){
                                layer.close(index);
                                parent.refreshTabByIndex(0);
                                parent.closeCurPage();
                            });

                        }else{
                            layer.msg(data.info, {icon: 2});
                        }
                    }
                });
            });
	    });
	},
	/**
	 * 初始化上传
	 */
	initFileUpload:function() {
		//上传方案初始化
		$("#UploadPlanFile").on("change", function() {
			var files = this.files;
			$.each(files, function(key, val) {
				var file = val;
				var name = file.name;
				var size = file.size, type = file.type || "", id =(file.lastModified + "").replace(/\W/g, '') + size + type.replace(/\W/g, '') + name.replace(/\W/g, '');
				if (!limitFileType(name)) {// 文件内容为空
					layer.alert("不接受此文件类型！");
					return;
				}else if (size==0) {// 文件内容为空
					layer.alert("文件内容不存在！");
					return;
				}else if (size > 1024 * 1024 * 1024 * 2) {// 大于2G
					layer.alert("文件过大！");
					return;
				} else if (edit_project.fileArrayPlan.indexOf(id) != -1) {
					layer.alert("文件已存在！");
					return;
				}else{
					$("#UploadPlanFile").parents("dl").next().find("input").val(name);
					edit_project.fileArrayPlan.push(id);
					edit_project.fileArrayPlan[id] = file;
				}
			});
		});
		//上传进度初始化
		$("#UploadProgressFile").on("change", function() {
			var files = this.files;
			$.each(files, function(key, val) {
				var file = val;
				var name = file.name;
				var size = file.size, type = file.type || "", id =(file.lastModified + "").replace(/\W/g, '') + size + type.replace(/\W/g, '') + name.replace(/\W/g, '');
				if (size==0) {// 文件内容为空
					layer.alert("文件内容不存在！");
					return;
				}else if (size > 1024 * 1024 * 1024 * 2) {// 大于2G
					layer.alert("文件过大！");
					return;
				} else if (edit_project.fileArrayPro.indexOf(id) != -1) {
					layer.alert("文件已存在！");
					return;
				} else {
					$("#UploadProgressFile").parents("dl").next().find("input").val(name);
					edit_project.fileArrayPro.push(id);
					edit_project.fileArrayPro[id] = file;
				}
			});
		});
	},
	/**
	 * 展示添加方案框
	 */
	addPlan:function(){
		$(".plan_v .add_file").hide();
		$(".plan_v .add_plan").show();
	},
	/**
	 * 展示添加进度框
	 */
	addProgress:function(){
		edit_project.resetPro();
		$("#pro_lable").text("新增进度");
		$(".add_pro_file").hide();
		$(".add_pro").show();
	},
	
	progress_puuid:"0",
	progress_uuid:"",
	/**
	 * 点击维护进度
	 * @param uuid
	 * @param puuid
	 */
	maintain:function(uuid,puuid){
		edit_project.resetPro();
		$("#pro_lable").text("维护进度");
		$(".add_pro_file").hide();
		$(".add_pro").show();
		if(puuid=="0"){
			edit_project.progress_puuid=uuid;
		}
		edit_project.progress_uuid=uuid;
		var a = $('.aasdasdas').offset().top+150;
		 $('html,body').animate({
             scrollTop: a
         }, 200);
	},
	/**
	 * 保存方案
	 */
	savePlan:function() {
		// 保存数据
		var listData = [];
		edit_project.planObj={};
		var accTitle=$(".add_plan").find(".accessoryName").val();
		if (accTitle == undefined || accTitle.trim().length == 0) {
			layer.alert("未填写项目名称！");
			return;
		}
		var planDescribe=$(".add_plan").find(".planDescribe").val();
		edit_project.planObj.accTitle = accTitle;
		edit_project.planObj.planDescribe = planDescribe;
		edit_project.planObj.dataUuid=edit_project._OBJ.uuid;
		edit_project.planObj.dataName=edit_project._OBJ.proName;
		edit_project.planObj.accType=2;
		//上传中
		var loading = layer.load(0, { //icon支持传入0-2
		    shade: [0.5, 'gray'], //0.5透明度的灰色背景
		    content: '文件上传中',
		    success: function (layero) {
		        layero.find('.layui-layer-content').css({
		            'padding-top': '39px',
		            'width': '80px'
		        });
		    }
		});
		var uploadPath="project//"+edit_project._OBJ.uuid+"//plan"
		//上传文件
		edit_project.funFileUpload(edit_project.fileArrayPlan[0],edit_project.fileArrayPlan,uploadPath,"acessory");
		listData.push(edit_project.planObj);
		$.ajax({
			url : "/crm/accessory/saveAccessorys",
			dataType : "json",
			async : false,
			data : JSON.stringify(listData),
			contentType : "application/json;charset=UTF-8",
			type : "post",
			success : function(data) {
				layer.close(loading);
				if (data.status) {
					edit_project.resetPlan();
					$(".plan_v .add_file").show();
					$(".plan_v .add_plan").hide();
					layer.alert(data.count+"条记录保存成功！"+data.info);
					edit_project.findAccessory();
				} else {
					layer.alert('保存失败！'+data.info);
				}
			},
			error : function() {

			}
		});
	},
	resetPlan:function(){
		edit_project.planObj = null;
		edit_project.fileArrayPlan=[];
		$(".add_plan").find(".accessoryName").val("");
		$(".add_plan").find(".planDescribe").val("");
		$("#UploadPlanFile").parents("dl").next().find("input").val("");
	},
	/**
	 * 保存进度
	 */
	saveProgress:function() {
		// 保存数据
		edit_project.proObj={};
		var listData = [];
		var proTitle=$(".add_pro").find(".proTitle").val();
		if (proTitle == undefined || proTitle.trim().length == 0) {
			layer.alert("未填写进度标题！");
			return;
		}
		var nextStepTime=$(".add_pro").find(".nextStepTime").val();
		var proDescribe=$(".add_pro").find(".proDescribe").val();
		edit_project.proObj.proTitle = proTitle;
		edit_project.proObj.nextStepTime = nextStepTime;
		edit_project.proObj.proDescribe = proDescribe;
		edit_project.proObj.dataUuid=edit_project._OBJ.uuid;
		edit_project.proObj.dataName=edit_project._OBJ.proName;
		edit_project.proObj.searchPowerUserUuids=edit_project._OBJ.searchPowerUserUuids;
		edit_project.proObj.searchPowerUserName=edit_project._OBJ.searchPowerUserName;
		edit_project.proObj.editPowerUserUuids=edit_project._OBJ.editPowerUserUuids;
		edit_project.proObj.editPowerUserName=edit_project._OBJ.editPowerUserName;
		edit_project.proObj.proType=2;
		edit_project.proObj.puuid=edit_project.progress_puuid;
		
		//上传中	
		var loading = layer.load(0, { //icon支持传入0-2
		    shade: [0.5, 'gray'], //0.5透明度的灰色背景
		    content: '文件上传中',
		    success: function (layero) {
		        layero.find('.layui-layer-content').css({
		            'padding-top': '39px',
		            'width': '80px'
		        });
		    }
		});
		var uploadPath="project//"+edit_project._OBJ.uuid+"//progress"
		//上传文件
		edit_project.funFileUpload(edit_project.fileArrayPro[0],edit_project.fileArrayPro,uploadPath,"progress");
		listData.push(edit_project.proObj);
		$.ajax({
			url : "/crm/progress/saveProgresss",
			dataType : "json",
			async : false,
			data : JSON.stringify(listData),
			contentType : "application/json;charset=UTF-8",
			type : "post",
			success : function(data) {
				layer.close(loading);
				if (data.status) {
					if(edit_project.progress_puuid!="0"){
						edit_project.changeReadStats();
					}
					$(".add_pro_file").show();
					$(".add_pro").hide();
					layer.alert(data.count+"条记录保存成功！"+data.info);
					edit_project.findProgress();
					edit_project.resetPro();
				} else {
					layer.alert('保存失败！'+data.info);
				}
			},
			error : function() {

			}
		});
	},
	resetPro:function(){
		edit_project.proObj = null;
		edit_project.fileArrayPro=[];
		edit_project.progress_puuid = "0";
		edit_project.progress_uuid = "";
		$("#pro_uuid").val("null");
		$(".add_pro").find(".proTitle").val("");
		$(".add_pro").find(".nextStepTime").val("");
		$(".add_pro").find(".proDescribe").val("");
		$("#UploadProgressFile").parents("dl").next().find("input").val("");
	},
	/**
	 * 检索项目方案和进度获取条件
	 */
	getPPParam:function() {
		var obj = {};
		obj.pageIndex = 1;
		obj.pageSize = 1000;
		var searchWord = {};
		searchWord.dataUuid = edit_project._OBJ.uuid;//  查询字段
		obj.conditions = JSON.stringify(searchWord);
		return obj;
	},
	/**
	 * 查询项目进度列表
	 * @param dataUuid
	 */
	findProgress:function(){
		$.ajax({
			//url : "/crm/retrieval/loadProgressGroupData", 
			url : "/crm/progress/loadProgressByDataUuid", 
			dataType : "json", 
			async : true,
			data : {"uuid":edit_project._OBJ.uuid},
			type : "post",
			success : function(data) {
				if(data.length>0){
					$(".add_pro_file").show();
					$(".add_pro").hide();
					var html='<tr class="first_tr"><th style="width:5%;">序号</th><th style="width:20%;">进度标题</th><th style="max-width:30%;">进度描述</th><th style="width:10%;">下一节点时间</th><th style="width:10%;">创建时间</th><th style="width:10%;">附件</th><th style="width:15%;">操作</th></tr>';
					var num1 = 0;
					var num2 = 0;
					$(data).each(function(key,val){
						if(val.puuid=="0"){
							if(key!=0){
								html+='<tr></tr>';
							}
							num1++;
							html+='<tr><td>第'+num1+'进度</td></tr>';
							if(key%2==0){
								html+='<tr>';
							}else{
								html+='<tr class="tr_shade">';
							}
							num2=0;
							html+='<td>'+num1+'</td>';
						}else{
							if(key%2==0){
								html+='<tr>';
							}else{
								html+='<tr class="tr_shade">';
							}
							num2++;
							html+='<td>'+num1+'.'+num2+'</td>';
						}
						html+='<td>'+val.proTitle+'</td>';
						html+='<td>'+val.proDescribe+'</td>';
						html+='<td>'+val.nextStepTime+'</td>';
						html+='<td>'+val.createTime+'</td>';
						var opter = "<td>";
						if(isBlank(val.proFilePath)){
							html += '<td>--</td>';
						}else{
							html+='<td>'+val.proFilePath.substring(val.proFilePath.lastIndexOf("/") + 1)+'</td>';
							opter+='<a onclick="preview(\''+val.proFilePath+'\',1)">预览</a><a onclick="downloadServer(\''+val.proFilePath+'\',1)">下载</a>';
						}
						if(val.readStats==0){
							opter+='<a onclick="edit_project.maintain(\''+val.uuid+'\',\''+val.puuid+'\')">维护</a>';
						}
						html += opter+"</td>";
						html+='</tr>';
					});
					$("#progressTable").html(html);
				}else{
					$(".add_pro_file").hide();
					$(".add_pro").show();
				}
			},
			error : function() {
				layer.msg("系统错误！", {icon: 2,closeBtn: 0 });;
			}
		});
	},
	/**
	 * 维护之后更改原进度状态
	 * @param uuid
	 */
	changeReadStats:function(){
		$.ajax({
			url : "/crm/progress/changeReadStats", // 请求的url地址
			dataType : "json", // 返回格式为json
			async : true,// 请求是否异步，默认为异步，这也是ajax重要特性
			data : {"uuid":edit_project.progress_uuid}, // 参数值
			type : "post", // 请求方式
			success : function(data) {
				console.log(data)
			},
			error : function() {
			}
		})
	},
	/**
	 * 查询项目方案列表
	 * @param dataUuid
	 */
	findAccessory:function(){
		$.ajax({
			url : "/crm/accessory/findBySpec", 
			dataType : "json", 
			async : true,
			data : edit_project.getPPParam(),
			type : "post",
			success : function(data) {
				if(data.total>0){
					$(".plan_v .add_file").show();
					$(".plan_v .add_plan").hide();
					var html='<tr class="first_tr"><th style="width:20%;">方案名称</th><th style="width:45%;">方案描述</th><th style="width:15%;">上传时间</th><th style="width:10%;">附件</th><th style="width:10%;"></th></tr>';
					$(data.rows).each(function(key,val){
						if(key%2==0){
							html+='<tr>';
						}else{
							html+='<tr class="tr_shade">';
						}
						html+='<td>'+val.accTitle+'</td>';
						html+='<td>'+val.planDescribe+'</td>';
						html+='<td>'+val.createTime+'</td>';
						if(isBlank(val.accFilePath)){
							html+='<td>--</td>';
							html+='<td>--</td>';
						}else{
							html+='<td>'+val.accFilePath.substring(val.accFilePath.lastIndexOf("/") + 1)+'</td>';
							html+='<td><a onclick="preview(\''+val.accFilePath+'\',1)">预览</a><a onclick="downloadServer(\''+val.accFilePath+'\',1)">下载</a></td>';
						}
						html+='</tr>';
					});
					$("#planTable").html(html);
				}else{
					$(".plan_v .add_file").hide();
					$(".plan_v .add_plan").show();
				}
			},
			error : function() {
				layer.msg("系统错误！", {icon: 2,closeBtn: 0 });;
			}
		});
	},
	/**
	 * 单文件上传
	 */
	funFileUpload:function(fileid,fileArray,uploadPath,fileType,onsuccess, onerror, onpause) {
		var file = fileArray[fileid], now = performance.now();
		if (!fileid || !file)
			return;
		onsuccess = onsuccess || function() {
			edit_project.funFileUpload(fileArray[0],fileArray,uploadPath,fileType);
		};

		onerror = onerror || function() {
			edit_project.funFileUpload(fileArray[fileArray.indexOf(fileid) + 1],fileArray,uploadPath,fileType);
		};
		onpause = onpause || function() {
			edit_project.funFileUpload(fileArray[fileArray.indexOf(fileid) + 1],fileArray,uploadPath,fileType);
		};
		if (file.flagPause == true) {
			onpause.call(fileid);
			return;
		}
		// objStateElement.wait(fileid);
		// 文件分割上传
		// 文件大小和分割起点
		// 注释的是本地存储实现
		var size = file.size, start = localStorage[fileid] * 1 || 0;
		// start = $("filelist_" + fileid).filesize;
		if (size == start) {
			// 已经传过了
			fileArray.shift();
			if (delete fileArray[fileid])
			// objStateElement.success(fileid, now);
			// 回调
			onsuccess.call(fileid, {});
			localStorage.clear();
			return;
		}

		var funFileSize = function() {
			if (file.flagPause == true) {
				onpause.call(fileid);
				return;
			}
			var data = new FormData();
			var name = file.name.replace(/[\@\#\$\%\^\&\*\{\}\:\"\L\<\>\?\ ]/g ,'');
			data.append("fileName", encodeURIComponent(name));
			data.append("fileid", fileid);
			data.append("myFile", file.slice(start, start + edit_project.fileSplitSize));
			data.append("start", start + "");
			data.append("flag",(start + edit_project.fileSplitSize)>=size?"COMPLETE":"UPLOAD");
			data.append("uploadPath",uploadPath);
			var p = "?name=" + encodeURIComponent(name) + "&fileid" + fileid + "&start" + start;
			// XMLHttpRequest 2.0 请求
			var xhr = new XMLHttpRequest();
			xhr.open("post", "/crm/fileUpload", false);
			// .setRequestHeader("X_Requested_With",
			// location.href.split("/")[5].replace(/[^a-z]+/g,"$"));
			// xhr.setRequestHeader("Content-type", "multipart/form-data");
			// 上传进度中
			xhr.upload.addEventListener("progress", function(e) {
				// objStateElement.backgroundSize(fileid, (e.loaded + start) / size
				// * 100);
			}, false);
			// ajax成功后
			xhr.onreadystatechange = function(e) {
				if (xhr.readyState == 4) {
					if (xhr.status == 200) {
						try {
							var json = JSON.parse(xhr.responseText);
							temp = 2;
						} catch (e) {
							// objStateElement.error(fileid);
							return;
						}
						// var json = JSON.parse(xhr.responseText);
						if (!json || !json.succ) {
							// objStateElement.error(fileid);
							onerror.call(fileid, json);
							return;
						}

						if (start + edit_project.fileSplitSize >= size) {
							// 超出，说明全部分割上传完毕
							// 上传队列中清除者一项
							fileArray.shift();
							if (delete fileArray[fileid])
							// objStateElement.success(fileid, now);
							// 回调
							onsuccess.call(fileid, json);
							filePath = json.data.savePath;
							if(fileType=="acessory"){
								edit_project.planObj.accFilePath = filePath;
							}else if(fileType=="progress"){
								edit_project.proObj.proFilePath = filePath;
							}
							localStorage.clear();
						} else {
							// 尚未完全上传完毕
							// 改变下一部分文件的起点位置
							start += edit_project.fileSplitSize;
							// 存储上传成功的文件点，以便出现意外的时候，下次可以断点续传
							localStorage.setItem(fileid, start + "");
							// 上传下一个分割文件
							funFileSize();

						}
					} else {
						// objStateElement.error(fileid);
					}
				}
			};

			xhr.send(data);
		};
		// 文件分割上传开始
		funFileSize();
	}
}
